const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isAnon: false, //是否匿名
    maxPicNum: 9,
    maxTextLen: 500,
    maxTagsNum: 8, //最大标签数
    maxTagLen: 10, //最大标签长度
    picPaths: [],
    textVal: '', //说些什么文本
    tag: '', //单个标签
    tags: [] //标签集
  },
  pic_urls: [], //返回的外网图片地址
  //添加上传图片
  chooseImageTap: function () {
    var self = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'], // 按钮的文字数组，数组长度最大为 6
      itemColor: "#00000", // 按钮的文字颜色
      success: function (res) { // 接口调用成功的回调函数
        if (res.tapIndex == 0) {
          self.chooseWxImage('album');
        } else if (res.tapIndex == 1) {
          self.chooseWxImage('camera');
        }
      }
    })
  },
  // 图片本地路径
  chooseWxImage: function (type) {
    var self = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'], // 原图、压缩图
      sourceType: [type], // 选择图片的来源
      success: res => {
        //以下代码可以先进行本地上传并预览
        let picPaths = self.data.picPaths;
        let temp = res.tempFilePaths;
        let len = temp.length + picPaths.length;
        if (len <= self.data.maxPicNum) {
          picPaths = picPaths.concat(temp);
          self.setData({
            picPaths: picPaths
          })
        } else {
          wx.showToast({
            title: '超过上传限制',
            icon: 'error',
            duration: 2000
          })
        }
      }
    })
  },
  // 图片预览
  // previewImage: function(e){
  //   let picPaths = this.data.picPaths;
  //   wx.previewImage({
  //     current: e.currentTarget.id,// 当前显示图片的http链接
  //     urls: picPaths// 需要预览的图片http链接列表
  //   })
  // },

  //图片预览以及删除，跳转到图片界面
  previewImage: function (e) {
    var index = e.target.dataset.index;
    wx.navigateTo({
      url: 'picture?picPaths=' + this.data.picPaths + '&index=' + index,
    })
  },
  deleteImage: function (e) {
    var self = this;
    let picPaths = self.data.picPaths;
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      success: function (res) {
        if (res.confirm) {
          picPaths.splice(index, 1);
        } else if (res.cancel) {
          return false;
        }
        self.setData({
          picPaths: picPaths
        });
      }
    })
  },
  handleTextInput: function (e) {
    let value = e.detail.value;
    let len = parseInt(value.length);
    if (len <= this.data.maxTextLen) {
      this.setData({
        textVal: value
      })
    }
    if (len > this.data.maxTextLen) return;
  },
  handleTagInput: function (e) {
    let value = e.detail.value;
    let len = parseInt(value.length);
    if (len <= this.data.maxTagLen) {
      this.setData({
        tag: value
      })
    }
    if (len > this.data.maxTagLen) return;
    //console.log(this.data.textVal);
  },
  addTag: function () {
    let tags = this.data.tags;
    let tag = this.data.tag;
    if (tags.length <= this.data.maxTagsNum) {
      if (tag == "") {
        wx.showToast({
          title: '标签不可为空',
          icon: 'error',
          duration: 2000
        })
      } else {
        tags.push(tag);
        this.setData({
          tags: tags,
          tag: ""
        })
      }

    } else {
      wx.showToast({
        title: '标签已达上限',
        icon: 'error',
        duration: 2000
      })
    }
  },
  deleteTags: function (e) {
    var self = this;
    let tags = self.data.tags;
    var index = e.currentTarget.dataset.index; //获取当前长按标签下标
    wx.showModal({
      title: '提示',
      content: '确定要删除此标签吗？',
      success: function (res) {
        if (res.confirm) {
          tags.splice(index, 1);
        } else if (res.cancel) {
          return false;
        }
        self.setData({
          tags: tags
        });
      }
    })
  },
  // 复选框
  handleItemChange: function (e) {
    console.log(e);
    if (e.detail.value == "false") {
      this.setData({
        isAnon: true
      })
    } else {
      this.setData({
        isAnon: false
      })
    }
    console.log(this.data.isAnon)
  },
  uploadInfo: function () {
    var self = this;
    console.log(self.pic_urls);
    var data = {
      anon: self.data.isAnon,
      textBody: self.data.textVal,
      urls: self.pic_urls,
      tags: self.data.tags
    }
    app.wxapi('POST', "/wall/content/publish", data, 'application/x-www-form-urlencoded', res => {
      console.log(res);
      if (res.success) {
        self.setData({
          tags: "",
          picPaths: "",
          textVal: ""
        })
        wx.showToast({
          title: '上传成功',
          success: function () {
            console.log('haha');
            setTimeout(function () {
              //要延时执行的代码
              wx.navigateBack({
                delta: 1
              });
            }, 1000) //延迟时间
          }
        })
      } else {
        console.log("没有回应");
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '提交失败',
        });
      }
    }, (err) => {
      //调用服务端登录接口失败
      console.log(err.errMsg)
    })
  },
  upload: function () {
    var self = this;
    var picPaths = self.data.picPaths;
    if (self.data.textVal == "") {
      wx.showToast({
        title: '文本不可为空',
        icon: 'error',
        duration: 2000
      })
      return;
    }
    if (app.globalData.userInfo == null) {
      wx.showToast({
        title: '登录方可使用',
        icon: 'error',
        duration: 2000
      })
      return;
    }
    wx.showLoading({
      title: '正在上传中...',
      mask: true
    })
    if (picPaths.length == 0) {
      self.uploadInfo();
    } else {
      picPaths.forEach((v, i) => {
        wx.uploadFile({
          filePath: picPaths[i],
          name: 'image',
          url: app.globalData.URL + '/upload',
          success: (res) => {
            console.log(res);
            let url = JSON.parse(res.data).data;
            let pic_urls = self.pic_urls;
            pic_urls.push(url);
            self.setData({
              pic_urls: pic_urls
            })
            if (self.pic_urls.length == picPaths.length) {
              self.uploadInfo();
            }
            wx.hideLoading();
          }
        })
      })
    }


  },
  //   upload: function(e){
  //     var self = this;
  //     self.uploadImg();
  //     console.log(self.pic_urls);
  //     var data = {
  //       anno: false,
  //       delete: false,
  //       textBody: self.data.textVal,
  //       urls: self.pic_urls
  //     }
  //     app.wxapi('POST', "/wall/content/publishWall", data, res => {
  //       console.log(res);
  //       if (res.success) {
  //         self.setData({
  //           tags: "",
  //           picPaths: "",
  //           textVal: ""
  //         })
  //         wx.navigateBack({
  //           delta : 1
  //         });
  //       }else {
  //         wx.showModal({
  //           title: '提示',
  //           content: '提交失败',
  //         });
  //       }
  //     }, (err) => {
  //       //调用服务端登录接口失败
  //       console.log(err.errMsg)
  //     })
  //   }
})